package cn.bellychang.ood.mailsendproduct.bad;

import cn.bellychang.ood.mailsendproduct.Configuration;
import cn.bellychang.ood.mailsendproduct.ConfigurationKeys;
import cn.bellychang.ood.mailsendproduct.DBUtil;
import cn.bellychang.ood.mailsendproduct.MailUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @author ChangLiang
 * @date 2020/5/12
 */
public class PromotionMail {

    String sendMailQuery;

    String smtpHost;

    String altSmtpHost;

    String fromAddress;

    String toAddress;

    String subject;

    String message;

    String productID;

    String productDesc;

    public void setProductID(String productID) {
        this.productID = productID;
    }

    public void setProductDesc(String productDesc) {
        this.productDesc = productDesc;
    }

    private static Configuration config;

    private static final String NAME_KEY = "NAME";
    private static final String EMAIL_KEY = "EMAIL";


    public static void main(String[] args) {
        File f = new File(PromotionMail.class.getClassLoader().getResource("product_promotion.txt").getFile());
        boolean emailDebug = false;
        try {
            PromotionMail pe = new PromotionMail(f, emailDebug);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public PromotionMail(File file, boolean mailDebug) throws Exception {

        // 读取促销文件
        // 文件中只有一行用空格隔开， 例如 P8756 iPhone8
        readFile(file);

        config = new Configuration();

        setSMTPHost();
        setAltSMTPHost();

        setFromAddress();

        // 从数据库中读取用户列表
        setLoadQuery();
        // 向用户逐一发送邮件
        sendEMails(mailDebug, loadMailingList());
    }

    protected List loadMailingList() throws Exception {
        return DBUtil.query(this.sendMailQuery);
    }

    protected void configureEMail(HashMap userInfo) throws IOException {
        toAddress = (String) userInfo.get(EMAIL_KEY);
        if (toAddress.length() > 0) {
            setMessage(userInfo);
        }
    }

    protected void setMessage(HashMap userInfo) throws IOException {
        String name = (String) userInfo.get(NAME_KEY);
        subject = "您关注的产品降价了";
        message = "尊敬的 " + name + ", 您关注的产品 " + productDesc + " 降价了，欢迎购买!";
    }

    protected void sendEMails(boolean debug, List mailingList) throws IOException {
        System.out.println("开始发送邮件");
        if (mailingList != null) {
            Iterator iter = mailingList.iterator();
            while (iter.hasNext()) {
                configureEMail((HashMap) iter.next());
                try {
                    if (toAddress.length() > 0) {
                        MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, debug);
                    }
                } catch (Exception e) {
                    try {
                        MailUtil.sendEmail(toAddress, fromAddress, subject, message, altSmtpHost, debug);
                    } catch (Exception e2) {
                        System.out.println("通过备用 SMTP服务器发送邮件失败: " + e2.getMessage());
                    }
                }
            }
        } else {
            System.out.println("没有邮件发送");
        }
    }

    protected void setLoadQuery() throws Exception {
        sendMailQuery = "Select name from subscriptions "
                + "where product_id= '" + productID + "' "
                + "and send_mail=1 ";
        System.out.println("loadQuery set");
    }

    protected void setFromAddress() {
        fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN);
    }

    protected void setAltSMTPHost() {
        altSmtpHost = config.getProperty(ConfigurationKeys.ALTERNATIVE_SMTP_SERVER);

    }

    protected void setSMTPHost() {
        smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER);
    }

    protected void readFile(File file) throws IOException {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            String temp = br.readLine();
            String[] data = temp.split(" ");

            setProductID(data[0]);
            setProductDesc(data[1]);

            System.out.println("产品ID = " + productID + "\n");
            System.out.println("产品描述 = " + productDesc + "\n");

        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException(e.getMessage());
        } finally {
            br.close();
        }
    }
}
